﻿using ICSharpCode.TextEditor.Document;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ICSharpCode.TextEditor.Tests;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Gui.InsightWindow;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using System.IO;
using Sunny.UI;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace t_test
{
    public partial class Form1 : Form
    {
        public InsightWindow insightWindow;
        public Form1()
        {
            InitializeComponent();
            this.textEditorControl1.TextChanged += TextEditorControl1_TextChanged;
        }
        private void TextEditorControl1_TextChanged(object sender, EventArgs e)
        {
            textEditorControl1.Document.FoldingManager.UpdateFoldings(null, null);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            insightWindow = new InsightWindow(this, textEditorControl1);
            textEditorControl1.ShowVRuler = true;
            textEditorControl1.Encoding = System.Text.Encoding.Default;
            FileSyntaxModeProvider fsmp;
            //fsmp = new FileSyntaxModeProvider("../../source");
            //HighlightingManager.Manager.AddSyntaxModeFileProvider(fsmp);
            //textEditorControl1.SetHighlighting("C#");
            textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            textEditorControl1.BackColor = Color.YellowGreen;
            //textEditorControl1.ResetText();
            //textEditorControl1.Language=ICSharpCode.TextEditor.TextEditorControl.lang
            textEditorControl1.Document.FoldingManager.FoldingStrategy = new FoldingStrategyForCSharp();
            textEditorControl1.Document.FormattingStrategy = new DefaultFormattingStrategy();
        }

        private void textEditorControl1_Load(object sender, EventArgs e)
        {
            //.。
        }

        

        public class FoldingStrategyForCSharp : IFoldingStrategy
        {
            /// <summary>
            /// 生成代码折叠,对花括号{}，#region等的处理
            /// </summary>
            /// <param name="document">当前文档</param>
            /// <param name="fileName">文档名</param>
            /// <param name="parseInformation">Extra parse information, not used in this sample.</param>
            /// <returns>A list of FoldMarkers.</returns>
            public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
            {
                List<FoldMarker> list = new List<FoldMarker>();
                Stack<int> startLines = new Stack<int>();
                // Create foldmarkers for the whole document, enumerate through every line.
                for (int i = 0; i < document.TotalNumberOfLines; i++)
                {
                    // Get the text of current line.
                    string text = document.GetText(document.GetLineSegment(i));
                    if (text.Trim().StartsWith("#region")) // Look for method starts
                    {
                        startLines.Push(i);
                    }
                    if (text.Trim().StartsWith("#endregion")) // Look for method endings
                    {
                        int start = startLines.Pop();
                        // Add a new FoldMarker to the list.
                        // document = the current document
                        // start = the start line for the FoldMarker
                        // document.GetLineSegment(start).Length = the ending of the current line = the start column of our foldmarker.
                        // i = The current line = end line of the FoldMarker.
                        // 7 = The end column
                        list.Add(new FoldMarker(document, start, document.GetLineSegment(start).Length-1, i, 57, FoldType.Region, "..."));
                    }
                    //支持嵌套 {}
                    if (text.Trim().StartsWith("{")) // Look for method starts
                    {
                        startLines.Push(i);
                    }
                    if (text.Trim().StartsWith("}")) // Look for method endings
                    {
                        
                        if (startLines.Count > 0)
                        {
                            int start = startLines.Pop();
                            var ii = document.GetLineSegment(start).Length-1;

                            list.Add(new FoldMarker(document, start,ii, i, 57, FoldType.Region, "..."));
                        }
                    }

                    // /// <summary>
                    if (text.Trim().StartsWith("/// <summary>")) // Look for method starts
                    {
                        startLines.Push(i);
                    }
                    if (text.Trim().StartsWith("/// <returns>")) // Look for method endings
                    {
                        int start = startLines.Pop();
                        //获取注释文本（包括空格）
                        string display = document.GetText(document.GetLineSegment(start + 1).Offset, document.GetLineSegment(start + 1).Length);
                        //remove ///
                        display = display.Trim().TrimStart('/');
                        list.Add(new FoldMarker(document, start, document.GetLineSegment(start).Length, i, 57, FoldType.TypeBody, display));
                    }
                }
                
                return list;
            }
        }
        //textEditorControl1.ActiveTextAreaControl.BackColor = Color.YellowGreen;
        //    Font font = new Font(FontFamily.GenericMonospace, 12, FontStyle.Regular);
        //textEditorControl1.Font=font;

        //    textEditorControl1.ForeColor = Color.Yellow;

        //    //textEditorControl1.ActiveTextAreaControl.BackgroundImage = ;
        //    //textEditorControl1.
        //    textEditorControl1.Margin = new Padding(0,0,0,0);
        //textEditorControl1.Text = "fgffffffffffffff";
        //    textEditorControl1.TextEditorProperties.ShowTabs=false;
        //    FoldingManagerTests foldingManagerTests = new FoldingManagerTests();
        ////foldingManagerTests.SetUp(textEditorControl1.Document,textEditorControl1.Document.FoldingManager);
        //TextMarkerTests textMarkerTests = new TextMarkerTests();
        //textMarkerTests.document = textEditorControl1.Document;
        //    //textMarkerTests.document.TextEditorProperties.CaretLine = true; //指示当前光标的竖线
        //    textMarkerTests.document.TextEditorProperties.ShowMatchingBracket = true;
        //    //textMarkerTests.SetUp();
        //    textEditorControl1.Refresh();
        private void uiButton1_Click(object sender, EventArgs e)
        {
            insightWindow.ShowInsightWindow();
            BlockCommentTests textMarkerTests = new BlockCommentTests();
            //textMarkerTests.Init();
            textMarkerTests.document = textEditorControl1.Document;
            //textMarkerTests.EntireCommentSelected();
            
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog =new OpenFileDialog();
            fileDialog.Filter = "CSharp files (*.cs)|*.cs|All files (*.*)|*.*";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                //Read the contents of the file into a stream
                var fileStream = fileDialog.OpenFile();

                using (StreamReader reader = new StreamReader(fileStream))
                {
                    textEditorControl1.Text = reader.ReadToEnd();
                }
            }
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Filter = "CSharp files (*.cs)|*.cs|All files (*.*)|*.*";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                //Read the contents of the file into a stream
                File.WriteAllText(fileDialog.FileName, textEditorControl1.Text);
            }
        }
    }
}
